//点击表单外就关闭表单
$(() => {
    //使body的minWidth和浏览器高度一致
    $(document.body).css('minHeight', window.innerHeight);
    //点击body使显示的表单消失
    $(document.body).on('click', function (e) {
        //点击的不是表单本身
        if ($(e.target).parents('.form-box').length === 0
            && !$(e.target).hasClass('form-box')
            //忽略alert的关闭
            && $(e.target).parents('.tip-alert').length === 0
            //忽略所有按钮的点击
            && e.target.tagName !== 'BUTTON') {
            let form = $('.form-area .show');
            if (form.length >= 1) {
                if (form.length == 2) form = form.eq(1);
                form.removeClass(form.attr('class').split(' ')[2] + '-slide-down show')
                    .addClass('fade-out');

                setTimeout(() => {
                    form.addClass('hide');
                }, 500);
                $('.sale .order-detail').html('');
            }
        }
    });
});


//获取数据
let DATA = {};
$(() => {
    let server = 'http://www.fjemiot.cn/erp/',
        max = 10000;
    $.ajax({
        url: server + 'products',
        data: 'pageNum=1&pageSize=' + max,
        success: (reply) => {
            let {...p} = reply;
            DATA['product'] = p['products'];
            for (let product of reply['products']) product['name'] = product['brand'] + '-' + product['type'];
            $(document.body).append(datalistgen('product-list', reply['products']));
        },
        error: (reply) => {
            console.log(reply);
        }
    });
    $.ajax({
        url: server + 'customers',
        data: 'pageNum=1&pageSize=' + max,
        success: (reply) => {
            let {...c} = reply;
            DATA['customer'] = c['customers'];
            $(document.body).append(datalistgen('customer-list', reply['customers']));
        },
        error: (reply) => {
            console.log(reply);
        }
    });
    $.ajax({
        url: server + 'employees',
        data: 'pageNum=1&pageSize=' + max,
        success: (reply) => {
            let {...e} = reply;
            DATA['employee'] = e['employees'];
            $(document.body).append(datalistgen('employee-list', reply['employees']));
        },
        error: (reply) => {
            console.log(reply);
        }
    });
});

$(() => {
    let server = 'http://www.fjemiot.cn/erp/',
        $saleView = $('.sale-view'),
        $examineView = $('.examine-sale-view');

    let titles = {
            orderMaster: ['订单编号', '客户编号', '销售员编号', '日期', '分切费', '运费', '总价', '状态']
        },
        viewMessage = {
            orderMaster: {
                url: server + 'orderMaster',
                title: '销售单',
                view: $saleView,
                table: 'value',
                titles: titles.orderMaster,
                func: (reply) => {
                    $saleView.html('');
                    delete reply['orderDetail'];
                }
            },
            examine: {
                url: server + 'orderMaster',
                title: '审核',
                view: $examineView,
                table: 'value',
                titles: titles.orderMaster,
                func: (reply) => {
                    let examineArray = [];
                    $examineView.html('');
                    delete reply['orderDetail'];
                    for (let order of reply['value'])
                        if (order['state'] == 0)
                            examineArray.push(order);
                        //过滤
                    reply['value'] = examineArray;
                }
            }
        };


    for (let view in viewMessage) {
        viewMessage[view]['data'] = {pageNum:1, pageSize:15};
        initialize(viewMessage[view]);
    }

    //choose tr
    let $rightContain = $('.right-contain'),
        $formArea = $('.form-area');
    $rightContain.on('click', '.table-show tr', function (e) {
        $('.table-show .select-tr').removeClass('select-tr');
        $(this).addClass('select-tr');
    });

    $formArea.on('click', '.detail-show tr', function (e) {
        $('.detail-show .select-tr').removeClass('select-tr');
        $(this).addClass('select-tr');
    });

    $rightContain.on('click', 'button', function (e) {
        let types = e.target.classList.item(0).split('-'),
            form = $('.form-area .' + types[1]);
        if (types[0] == 'add') {
            window.operation = 'add';
            form.find('.submit-area span').text('￥0');
            form.find('input').each((i, tag) => {
                if (i == 0) {
                    $(tag).removeAttr('readonly');
                    $(tag).val('');
                    $(tag).attr('readonly', 'readonly')
                        .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                } else {
                    $(tag).val('');
                }
            });
            form.removeClass('hide fade-out').addClass(types[1] + '-slide-down show');

        } else if (types[0] == 'upd') {
            window.operation = 'upd';
            let dataLine = $('.right-contain .table-show .select-tr');
            if (dataLine.length == 1) {
                let datas = dataLine.children();
                form.find('.submit-area span').text('');
                form.find('.order-detail').html('');
                form.removeClass('hide fade-out').addClass(types[1] + '-slide-down show');
                form.find('input').each((i, tag) => {
                    if (i == 0) {
                        $(tag).removeAttr('readonly');
                        $(tag).val(datas.eq(0).text());
                        $(tag).attr('readonly', 'readonly')
                            .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                    }
                    if (1 <= i && i <= 2) {
                        $(tag).val(datas.eq(i).text())
                    }
                    if (3 <= i) {
                        $(tag).val(datas.eq(i + 1).text())
                    }
                });
            } else {
                tip.alert('未选中行', '销售', 'warn');
            }

        } else if (types[0] == 'del') {
            let dataLine = $('.right-contain .table-show .select-tr');
            if (dataLine.length == 1) {
                $.ajax({
                    url: server + 'orderMaster/' + dataLine.children().eq(0).text(),
                    type: 'delete',
                    success: (reply) => {
                        if (reply == '1001') {
                            tip.alert('删除成功', '销售', 'success');
                            for (let view in viewMessage) initialize(viewMessage[view]);
                        } else {
                            tip.alert('删除失败', '销售', 'error');
                        }
                    },
                    error: (reply) => {
                        console.log(reply);
                        tip.alert(reply['responseJSON']['message'], '销售明细', 'error', 5000);
                    }
                });
            } else {
                tip.alert('未选中行', '销售', 'warn');
            }
        } else if (types[0] == 'show') {
            let dataLine = $('.right-contain .select-tr'),
                $detailForm = $('.form-area .' + types[1]),
                order,
                view;

            if (dataLine.length == 1) {
                order = dataLine.children().eq(0).text();
                view = $('.form-area .saleDetail-view');
                $detailForm.find('.title span').text(order);
                initializeDetail({
                    url: server + 'orderDetail',
                    title: '销售明细',
                    order: order,
                    view: view,
                    table: 'value',
                    func: (reply) => {
                        view.html('');
                        for (let detail of reply['value']) {
                            delete detail['orderNo'];
                            detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                        }
                    },
                    titles: ['数量', '价格', '产品']
                });
                $detailForm.removeClass('fade-out hide').addClass(types[1] + '-slide-down show');
            } else {
                tip.alert('未选中行', '销售', 'warn');
            }
        }
    });


    //总价计算、显示
    $('.form-area .sale').on('blur', 'input.orderDetail-number', function (e) {
        let orderDetail = $(e.target).parents('.form-box').find('.order-detail .detail-line'),
            values = [], empty = false, orderSum = 0;

        orderDetail.each((i, tag) => {
            let inputs = $(tag).find('input'),
                dvalues = {};
            inputs.each((j, tag2) => {
                if (tag2 != undefined) {
                    let value = tag2.value.trim();
                    dvalues[tag2.getAttribute('name')] = value;
                    if (value == '') empty = true;
                }
            });
            values.push(dvalues);
        });

        if (!empty) {
            for (let detail of values) {
                for (let product of DATA['product']) {
                    if (detail['productNo'] == product['productNo']) {
                        orderSum += product['price'] * detail['number'];
                    }
                }
            }
            console.log(orderSum);
            $(e.target).parents('.form-box').find('.submit-area span').text('￥' + orderSum);
        }
    });
    //订单增改
    $('.form-box .order-submit').click(function () {
        let orderMaster = $(this).parents('.form-box').find('.order-master input'),
            orderDetail = $(this).parents('.form-box').find('.order-detail .detail-line'),
            empty = false,
            date,
            values = {master: {}, detail: []};

        orderMaster.each((i, tag) => {
            let value = tag.value.trim();
            values['master'][tag.getAttribute('name')] = value;
            if (value == '' && i != 0) empty = true;
        });
        orderDetail.each((i, tag) => {
            let inputs = $(tag).find('input'),
                dvalues = {};
            inputs.each((j, tag2) => {
                if (tag2 != undefined) {
                    let value = tag2.value.trim();
                    dvalues[tag2.getAttribute('name')] = value;
                    if (value == '') empty = true;
                }
            });
            values['detail'].push(dvalues);
        });

        let orderSum = 0;
        if (!empty) {
            for (let detail of values['detail']) {
                for (let product of DATA['product']) {
                    if (detail['productNo'] == product['productNo']) {
                        detail['price'] = product['price'] * detail['number'];
                        orderSum += detail['price'];
                        detail['product'] = {};
                        detail['product']['productNo'] = detail['productNo'];
                    }
                }
            }
            date = new Date();
            if (window.operation == 'add') values['master']['state'] = 0;
            values['master']['orderSum'] = orderSum;
            values['master']['date'] = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

            let finalData = values['master'];
            finalData['orderDetails'] = values['detail'];
            $.ajax({
                url: server + 'orderMaster',
                type: window.operation == 'add' ? 'post' : 'put',
                data: JSON.stringify(finalData),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    let message = window.operation == 'add' ? '添加' : '修改';
                    if (reply == '1001') {
                        tip.alert(message + '成功', '销售', 'success');

                        for (let view in viewMessage) initialize(viewMessage[view]);
                        document.body.click();
                    } else {
                        tip.alert(message + '失败', '销售', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply['responseJSON']['message']);
                    tip.alert('有重复产品', '销售', 'error', 5000);
                }
            });
        } else {
            tip.alert('输入不能为空', '销售', 'warn');
        }
    });

    //订单明细的增删改
    $formArea.on('click', 'button', function (e) {
        let types = e.target.classList.item(0).split('-');
        if (types[0] == 'add') {
            window.operation = 'add';
            $('.form-area .saleDetailForm input').each((i, tag) => {
                if (i == 0) $(tag).removeAttr('readonly').css('backgroundColor', '#f7f7f7').css('color', '#aaa');

                $(tag).val('');

            });
            $('.form-area .saleDetailForm')
                .removeClass('fade-out hide')
                .addClass('saleDetailForm-slide-down show')
                .attr('orderNo', $(e.target).parents('.form-box').find('.title span').text());
        } else if (types[0] == 'upd') {
            window.operation = 'upd';
            let dataLine = $('.form-area .detail-show .select-tr');
            if (dataLine.length == 1) {
                let trs = dataLine.children(),
                    inputs = $('.form-area .saleDetailForm input');
                inputs.eq(0).val(trs.eq(2).text().split('-')[0]);
                inputs.eq(1).val(trs.eq(0).text());
                inputs.eq(0).attr('readonly', 'readonly')
                    .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                $('.form-area .saleDetailForm')
                    .removeClass('fade-out hide')
                    .addClass('saleDetailForm-slide-down show')
                    .attr('orderNo', $(e.target).parents('.form-box').find('.title span').text());
            } else {
                tip.alert('未选中行', '销售明细', 'warn');
            }

        } else if (types[0] == 'del') {

        }
    });

    //订单明细增改
    $('.saleDetail-submit').click(function () {
        let values = {}, empty = false;
        $(this).parent().find('input').each((i, tag) => {
            let value = tag.value.trim();
            values[tag.getAttribute('name')] = value;
            if (value == '') empty = true;
        });
        if (!empty) {
            let productArray = DATA['product'],
                view = $('.form-area .saleDetail-view');
            values['product'] = {};
            values['product']['productNo'] = values['productNo'];
            values['orderNo'] = $(this).parent().attr('orderNo');

            for (let p of productArray) {
                if (p['productNo'] == values['productNo']) {
                    values['price'] = p['price'] * values['number'];
                }
            }

            $.ajax({
                url: server + 'orderDetail',
                type: window.operation == 'add' ? 'post' : 'put',
                data: JSON.stringify(values),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    let message = window.operation == 'add' ? '添加' : '修改';
                    if (reply == '1001') {
                        tip.alert(message + '成功', '销售明细', 'success');
                        initializeDetail({
                            url: server + 'orderDetail',
                            title: '销售明细',
                            order: values['orderNo'],
                            view: view,
                            table: 'value',
                            func: (reply) => {
                                view.html('');
                                for (let detail of reply['value']) {
                                    delete detail['orderNo'];
                                    detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                                }
                            },
                            titles: ['数量', '价格', '产品']
                        });
                        document.body.click();
                    } else {
                        tip.alert(message + '失败', '销售明细', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply);
                    tip.alert('已有该产品', '销售明细', 'error', 5000);
                }
            });
        } else {
            tip.alert('输入不能为空', '销售明细', 'warn');
        }
    });

    //订单明细删除
    $('.del-saleDetail').click(function () {
        let dataLine = $('.form-area .detail-show .select-tr'),
            view = $('.form-area .saleDetail-view');
        if (dataLine.length == 1) {
            let orderNo = $(this).parents('.form-box').find('.title span').text(),
                productNo = dataLine.children().eq(2).text().split('-')[0];
            $.ajax({
                url: server + 'orderDetail/' + orderNo + '/' + productNo,
                type: 'delete',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('删除成功', '销售明细', 'success');
                        initializeDetail({
                            url: server + 'orderDetail',
                            title: '销售明细',
                            order: orderNo,
                            view: view,
                            table: 'value',
                            func: (reply) => {
                                view.html('');
                                for (let detail of reply['value']) {
                                    delete detail['orderNo'];
                                    detail['product'] = detail['product']['productNo'] + '-' + detail['product']['brand'] + '-' + detail['product']['type'];
                                }
                            },
                            titles: ['数量', '价格', '产品']
                        });
                    } else {
                        tip.alert('删除失败', '销售明细', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply);
                    tip.alert(reply['responseJSON']['message'], '销售明细', 'error', 5000);
                }
            });
        } else {
            tip.alert('未选中行', '销售明细', 'warn');
        }
    });

    //审核
    $('.examine-sale').click(() => {
        let dataLine = $('.examine-sale-view .select-tr');
        if (dataLine.length == 1) {
            let ordeerInput = $('.form-area .examine input');
            ordeerInput.removeAttr('readonly');
            ordeerInput.val(dataLine.children().eq(0).text());
            ordeerInput.attr('readonly', 'readonly').css('backgroundColor', '#aaa').css('color', '#f7f7f7');
            $('.form-area .examine').removeClass('fade-out hide').addClass('examine-slide-down show');
        } else {
            tip.alert('未选中行', '审核', 'warn');
        }
    });

    $('.examine-submit').click(() => {
        let state = $('.form-area .examine select').val(),
            orderNo = $('.form-area .examine input').val();

        if (state != 0) {
            $.ajax({
                url: server + 'orderMaster',
                type: 'put',
                data: JSON.stringify({orderNo: orderNo, state: state}),
                dataType: 'json',
                contentType: 'application/json',
                success: (reply) => {
                    if (reply == '1001') {
                        tip.alert('修改成功', '销售', 'success');
                        for (let view in viewMessage) initialize(viewMessage[view]);
                        document.body.click();
                    } else {
                        tip.alert('修改失败', '销售', 'error');
                    }
                },
                error: (reply) => {
                    console.log(reply['responseJSON']['message']);
                    tip.alert(reply['responseJSON']['message'], '销售', 'error', 5000);
                }
            });
        } else {
            document.body.click();
        }
    });
});

// sale form
$(() => {
    let $saleForm = $('.form-area .sale'),
        detailHtml = '<div class="detail-line"><div class="input-group"><label>产品编号:<input type="number" id="product-number" list="product-list" placeholder="产品编号" name="productNo"></label></div><div class="input-group"><label >数量:<input class="orderDetail-number" type="number" placeholder="数量" name="number"></label></div></div>';
    //add detail form
    $saleForm.find('.add-detail').click(() => {
        if (window.operation == 'add') $saleForm.find('.order-detail').append(detailHtml);
    });
});
